import car from '../page/home/car'
import actions from './actions'
import actionsType from './actionsType'
const initState = {
  list: [],
  carList: []
}
// 7.使用状态管理容器redux，异步请求接口数据并实现列表数据的持久化
const reducer = (state = initState, action) => {
  const { type, payload } = action
  let { list, carList } = state
  switch (type) {
    // 设置列表数据
    case actionsType.SET_LIST:
      return {
        ...state,
        list: payload
      };
    // 设置收藏状态
    case actionsType.SET_COLLECT:

      const item = list.find(v => v.id === payload.id)
      item.isCollect = !item.isCollect

      return {
        ...state,
        list: [...list]
      };
    // 添加购物车  存在就数量+  不存在推入新数据
    case actionsType.ADD_CAR_LIST:

      const carItem = carList.find(v => v.id === payload.id)

      if (carItem) {
        carItem.count++
      } else {
        carList.push({
          ...payload,
          count: 1,
          checked: false
        })
      }

      return {
        ...state,
        carList: [...carList]
      };
    // 删除购物车一项数据
    case actionsType.DELETE_CAR_LIST:
      const newCarList = carList.filter(item => item.id !== payload.id)
      return {
        ...state,
        carList: [...newCarList]
      };
    // 减少一项数据的数量 
    // 数量<=1  直接删除
    case actionsType.SUB_CAR_LIST:
      const item1 = carList.find(item => item.id === payload.id)
      if (item1.count <= 1) {
        carList = carList.filter(item => item.id !== payload.id)
      } else {
        item1.count--
      }
      return {
        ...state,
        carList: [...carList]
      }
    // 切换单个单选状态
    case actionsType.SWITCH_CAR_LIST:
      const item2 = carList.find(item => item.id === payload.id)
      item2.checked = !item2.checked
      return {
        ...state,
        carList: [...carList]
      }
    // 切换所有单选状态
    case actionsType.SWITCH_CAR_LIST_ALL:
      carList.forEach(v => {
        v.checked = payload.checked
      })
      return {
        ...state,
        carList: [...carList]
      }
    default:
      return { ...state }
  }
}


export default reducer